import pandas as pd
from sklearn.cluster import KMeans, AgglomerativeClustering, SpectralClustering, Birch
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
import seaborn as sns
import os

# 读取数据集
df = pd.read_csv("new_file_with_scores_kmeans.csv")

# 定义特征列
features = ['Q3', 'Q4', 'Q5', 'Q6', 'Q11', 'kmeans_label']

# 定义轮廓系数评估函数
def silhouette_scorer(estimator, X):
    labels = estimator.fit_predict(X)
    score = silhouette_score(X, labels)
    return score

# 创建要尝试的无监督学习算法和参数网格
algorithms = {
    'KMeans': (KMeans(), {'n_clusters': range(3, 11)}),
    'AgglomerativeClustering': (AgglomerativeClustering(), {'n_clusters': range(3, 11)}),
    'SpectralClustering': (SpectralClustering(), {'n_clusters': range(3, 11)}),
    'Birch': (Birch(), {'n_clusters': range(3, 11)}),
    'GaussianMixture': (GaussianMixture(), {'n_components': range(3, 11)})
}

# 执行网格搜索以确定每个算法的最佳聚类数量
results = {}
for name, (model, param_grid) in algorithms.items():
    grid_search = GridSearchCV(model, param_grid=param_grid, scoring=silhouette_scorer)
    grid_search.fit(df[features])
    best_estimator = grid_search.best_estimator_
    best_score = grid_search.best_score_
    best_params = grid_search.best_params_
    results[name] = {'best_estimator': best_estimator, 'best_score': best_score, 'best_params': best_params}

import pandas as pd
import matplotlib.pyplot as plt
# 提取数据
# 提取数据
# 提取数据
names = list(results.keys())
scores = [result['best_score'] for result in results.values()]
parameters = [result['best_params']['n_clusters'] if 'n_clusters' in result['best_params'] else result['best_params']['n_components'] for result in results.values()]

# 提取不同 n_clusters 的数值
n_clusters_values = []
for name, (model, param_grid) in algorithms.items():
    if 'n_clusters' in param_grid:
        n_clusters_values.append(list(param_grid['n_clusters']))

# 创建图表
plt.figure(figsize=(10, 6))

# 绘制柱状图
for i in range(len(names)):
    color = 'red' if names[i] == 'KMeans' else 'skyblue'
    plt.bar([f"{names[i]} (n={n})" for n in n_clusters_values[i]], scores[i], color=color)

plt.xlabel('Algorithm (n_clusters)')
plt.ylabel('Best Score')
plt.title('Best Score of Different Clustering Algorithms')

# 在柱状图上显示最佳聚类数量
for i in range(len(names)):
    for j, score in enumerate(scores[i]):
        plt.text(f"{names[i]} (n={n_clusters_values[i][j]})", score, f'n_clusters={n_clusters_values[i][j]}', ha='center', va='bottom')

# 显示图例
plt.legend(['Best Score'])

# 显示图形
plt.show()

names = list(results.keys())
scores = [result['best_score'] for result in results.values()]
parameters = [result['best_params']['n_clusters'] if 'n_clusters' in result['best_params'] else result['best_params']['n_components'] for result in results.values()]

# 创建图表
plt.figure(figsize=(10, 6))

# 绘制柱状图
for i in range(len(names)):
    color = 'red' if names[i] == 'KMeans' else 'skyblue'
    plt.bar(names[i], scores[i], color=color)

plt.xlabel('Algorithm')
plt.ylabel('Best Score')
plt.title('Best Score of Different Clustering Algorithms')

# 在柱状图上显示最佳聚类数量
for i in range(len(names)):
    plt.text(names[i], scores[i], f'n_clusters={parameters[i]}', ha='center', va='bottom')

# 显示图例
plt.legend(['Best Score'])

# 显示图形
plt.show()
